package cn.dyp.com.systemsetting.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.util.DisplayMetrics;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import java.util.Locale;

import cn.dyp.com.systemsetting.R;

//系统设置Fragment类

/*
改动：把ChangeLanguage和这个程序融合了
问题：语言切换和自动手动切换无法保存
 */

public class SettingFragment extends PreferenceFragment implements
        OnPreferenceChangeListener, OnPreferenceClickListener {
    private static final String LANGUAGE = "language";
    private static final String LANGUAGEGROUP = "language_group";

    private static final String AUTO = "auto";
    private static final String AUTOGROUP = "auto_group";

    private static final String CO2 = "co2";
    private static final String CO2_MIN = "co2_min";
    private static final String CO2_MAX = "co2_max";

    private static final String LIGHT = "light";
    private static final String LIGHT_MIN = "light_min";
    private static final String LIGHT_MAX = "light_max";

    private static final String AIR = "air";
    private static final String AIR_T_MIN = "air_t_min";
    private static final String AIR_T_MAX = "air_t_max";
    private static final String AIR_H_MIN = "air_h_min";
    private static final String AIR_H_MAX = "air_h_max";

    private static final String SOIL = "soil";
    private static final String SOIL_T_MIN = "soil_t_min";
    private static final String SOIL_T_MAX = "soil_t_max";
    private static final String SOIL_H_MIN = "soil_H_min";
    private static final String SOIL_H_MAX = "soil_H_max";

    private EditTextPreference mLanguageETP;
    private EditTextPreference mAutoETP;
    private EditTextPreference mCO2ETP;
    private EditTextPreference mLightETP;
    private EditTextPreference mAirETP;
    private EditTextPreference mSoilETP;

    private EditText mCO2MinET;
    private EditText mCO2MaxET;
    private EditText mLightMinET;
    private EditText mLightMaxET;
    private EditText mAirTMinET;
    private EditText mAirTMaxET;
    private EditText mAirHMinET;
    private EditText mAirHMaxET;
    private EditText mSoilTMinET;
    private EditText mSoilTMaxET;
    private EditText mSoilHMinET;
    private EditText mSoilHMaxET;

    private RadioGroup mGroup;
    private String mCurrentState;
    private int mLanguageId ;
    private int mAutoId = R.id.radio0;
    private Locale mLocale;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference_setting);
        initView();
        setListener();
    }

    /**
     * 设置监听器
     *
     */
    private void setListener() {
        mLanguageETP.setOnPreferenceClickListener(this);
        mLanguageETP.setOnPreferenceChangeListener(this);
        mAutoETP.setOnPreferenceClickListener(this);
        mAutoETP.setOnPreferenceChangeListener(this);
        mCO2ETP.setOnPreferenceClickListener(this);
        mCO2ETP.setOnPreferenceChangeListener(this);
        mLightETP.setOnPreferenceClickListener(this);
        mLightETP.setOnPreferenceChangeListener(this);
        mAirETP.setOnPreferenceClickListener(this);
        mAirETP.setOnPreferenceChangeListener(this);
        mSoilETP.setOnPreferenceClickListener(this);
        mSoilETP.setOnPreferenceChangeListener(this);
    }

    /**
     * 初始化控件
     *
     */
    private void initView() {
        // 获取到控件
        mLanguageETP = (EditTextPreference) findPreference(LANGUAGE);
        mAutoETP = (EditTextPreference) findPreference(AUTO);
        mCO2ETP = (EditTextPreference) findPreference(CO2);
        mLightETP = (EditTextPreference) findPreference(LIGHT);
        mAirETP = (EditTextPreference) findPreference(AIR);
        mSoilETP = (EditTextPreference) findPreference(SOIL);
        saveAuto();
        // 设定初始值
        mCO2ETP.setSummary(getString(R.string.min_value) + getIntValue(CO2_MIN)
                + "		" + getString(R.string.max_value) + getIntValue(CO2_MAX));
        mLightETP.setSummary(getString(R.string.min_value) + getIntValue(LIGHT_MIN)
                + "		" + getString(R.string.max_value) + getIntValue(LIGHT_MAX));
        mAirETP.setSummary(getString(R.string.temp_min_value) + getIntValue(AIR_T_MIN)
                + "		" + getString(R.string.temp_max_value) + getIntValue(AIR_T_MAX)
                + '\n' + getString(R.string.humi_min_value) + getIntValue(AIR_H_MIN)
                + "		" + getString(R.string.humi_max_value) + getIntValue(AIR_H_MAX));
        mSoilETP.setSummary(getString(R.string.temp_min_value) + getIntValue(SOIL_T_MIN)
                + "		" + getString(R.string.temp_max_value) + getIntValue(SOIL_T_MAX)
                + '\n' + getString(R.string.humi_min_value) + getIntValue(SOIL_H_MIN)
                + "		" + getString(R.string.humi_max_value) + getIntValue(SOIL_H_MAX));
        Resources res = getResources();
        //获取系统的Configuration对象
        Configuration config = res.getConfiguration();
        if (config.locale.equals(Locale.CHINA)) {
            mLanguageETP.setSummary(R.string.chinese);
            mLanguageId = R.id.radio0;
        } else {
            mLanguageETP.setSummary(R.string.english);
            mLanguageId = R.id.radio1;
        }
        mLanguageETP.getSharedPreferences().edit()
                .putInt(LANGUAGEGROUP, mLanguageId).commit();
    }

    /**
     * 获取值
     *
     * @param key
     *            键
     * @return 键对应的值
     */
    private int getIntValue(String key) {
        SharedPreferences sh = getPreferenceManager().getSharedPreferences();
        return sh.getInt(key, 0);//当key不存在的时候，返回0；当key存在的时候，返回的是它存储的数据;
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        switch (preference.getKey()) {

            case LANGUAGE:
                saveLanguage();
                break;
            case AUTO:
                saveAuto();
                break;
            case CO2:
                saveCO2(preference);
                break;
            case LIGHT:
                saveLight(preference);
                break;
            case AIR:
                saveAir(preference);
                break;
            case SOIL:
                saveSoil(preference);
                break;
        }
        return true;
    }

    /**
     * 保存语言种类
     *
     *            基础的自定义UI
     */
    private void saveLanguage() {
        // 保存数据
        mLanguageETP.getEditor().putInt(LANGUAGEGROUP, mLanguageId)
                .commit();
        if (mLanguageId == R.id.radio0) {
            mLocale = Locale.CHINA;
        } else {
            mLocale = Locale.ENGLISH;
        }
        // 设置Summary的内容
        changeLanguage(mLocale);
        getActivity().finish();
    }

    /**
     * 切换语言
     *
     * @param locale
     *            本地语言的参数
     */
    private void changeLanguage(Locale locale) {
        Resources res = getResources();
        Configuration config = res.getConfiguration();
        config.locale = locale;//设置应用的语言为locale指定的语言
        DisplayMetrics dm = res.getDisplayMetrics();// 获得屏幕参数：主要是分辨率，像素等
        res.updateConfiguration(config, dm);
        getActivity().sendBroadcast(new Intent("systemsetting.language"));//发送广播，重启Activity
    }

    /**
     * 保存控制状态的方式
     *
     *            基础的自定义UI
     */
    private void saveAuto() {
        // 保存数据
        mAutoETP.getEditor().putInt(AUTOGROUP, mAutoId).commit();
        if (mAutoId == R.id.radio0) {
            mCurrentState = getString(R.string.manual);
        } else {
            mCurrentState = getString(R.string.auto);
        }
        // 设置Summary的内容
        mAutoETP.setSummary(mCurrentState);
    }

    /**
     * 保存CO2浓度的阀值
     *
     * @param preference
     *            基础的自定义UI
     */
    private void saveCO2(Preference preference) {
        // 初步判断输入框
        String minString = mCO2MinET.getText().toString().trim();
        if (minString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int min = Integer.valueOf(minString);
        String maxString = mCO2MaxET.getText().toString().trim();
        if (maxString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int max = Integer.valueOf(maxString);
        if (max < min) {
            showPrompt(getString(R.string.min_more_than_max));
            return;
        }
        // 保存数据
        preference.getEditor().putInt(CO2_MAX, max).commit();
        preference.getEditor().putInt(CO2_MIN, min).commit();
        // 设置Summary的内容
        ((EditTextPreference) preference)
                .setSummary(getString(R.string.min_value) + min + "		"
                        + getString(R.string.max_value) + max);
    }

    /**
     * 保存光照强度的阀值
     *
     * @param preference
     *            基础的自定义UI构造器
     */
    private void saveLight(Preference preference) {
        // 初步判断输入框
        String minString = mLightMinET.getText().toString().trim();
        if (minString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int min = Integer.valueOf(minString);
        String maxString = mLightMaxET.getText().toString().trim();
        if (maxString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int max = Integer.valueOf(maxString);
        if (max < min) {
            showPrompt(getString(R.string.min_more_than_max));
            return;
        }
        // 保存数据
        preference.getEditor().putInt(LIGHT_MAX, max).commit();
        preference.getEditor().putInt(LIGHT_MIN, min).commit();
        // 设置Summary的内容
        ((EditTextPreference) preference)
                .setSummary(getString(R.string.min_value) + min + "		"
                        + getString(R.string.max_value) + max);
    }

    /**
     * 保存空气温湿度的阀值
     *
     * @param preference
     *            基础的自定义UI构造器
     */
    private void saveAir(Preference preference) {
        // 初步判断输入框
        String minTString = mAirTMinET.getText().toString().trim();
        if (minTString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int minT = Integer.valueOf(minTString);
        String maxTString = mAirTMaxET.getText().toString().trim();
        if (maxTString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int maxT = Integer.valueOf(maxTString);
        if (maxT < minT) {
            showPrompt(getString(R.string.min_more_than_max));
            return;
        }
        String minHString = mAirHMinET.getText().toString().trim();
        if (minHString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int minH = Integer.valueOf(minHString);
        String maxHString = mAirHMaxET.getText().toString().trim();
        if (maxHString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int maxH = Integer.valueOf(maxHString);
        if (maxH < minH) {
            showPrompt(getString(R.string.min_more_than_max));
            return;
        }
        // 保存数据
        preference.getEditor().putInt(AIR_T_MAX, maxT).commit();
        preference.getEditor().putInt(AIR_T_MIN, minT).commit();
        preference.getEditor().putInt(AIR_H_MAX, maxH).commit();
        preference.getEditor().putInt(AIR_H_MIN, minH).commit();
        // 设置Summary的内容
        ((EditTextPreference) preference)
                .setSummary(getString(R.string.temp_min_value) + minT + "		"
                        + getString(R.string.temp_max_value) + maxT + '\n'
                        + getString(R.string.humi_min_value) + minH + "		"
                        + getString(R.string.humi_max_value) + maxH);
    }

    /**
     * 保存土壤温湿度的阀值
     *
     * @param preference
     *            基础的自定义UI构造器
     */
    private void saveSoil(Preference preference) {
        // 初步判断输入框
        String minTString = mSoilTMinET.getText().toString().trim();
        if (minTString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int minT = Integer.valueOf(minTString);
        String maxTString = mSoilTMaxET.getText().toString().trim();
        if (maxTString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int maxT = Integer.valueOf(maxTString);
        if (maxT < minT) {
            showPrompt(getString(R.string.min_more_than_max));
            return;
        }
        String minHString = mSoilHMinET.getText().toString().trim();
        if (minHString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int minH = Integer.valueOf(minHString);
        String maxHString = mSoilHMaxET.getText().toString().trim();
        if (maxHString.equals("")) {
            showPrompt(getString(R.string.min_max_value_not_empty));
            return;
        }
        int maxH = Integer.valueOf(maxHString);
        if (maxH < minH) {
            showPrompt(getString(R.string.min_more_than_max));
            return;
        }
        // 保存数据
        preference.getEditor().putInt(SOIL_T_MAX, maxT).commit();
        preference.getEditor().putInt(SOIL_T_MIN, minT).commit();
        preference.getEditor().putInt(SOIL_H_MAX, maxH).commit();
        preference.getEditor().putInt(SOIL_H_MIN, minH).commit();
        // 设置Summary的内容
        ((EditTextPreference) preference)
                .setSummary(getString(R.string.temp_min_value) + minT + "		"
                        + getString(R.string.temp_max_value) + maxT + '\n'
                        + getString(R.string.humi_min_value) + minH + "		"
                        + getString(R.string.humi_max_value) + maxH);
    }

    /**
     * 显示提示对话框
     *
     * @param string
     *            提示信息
     */
    private void showPrompt(String string) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.prompt);
        builder.setMessage(string);
        builder.setPositiveButton(getString(R.string.cancel), null);
        builder.show();
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        switch (preference.getKey()) {
            case LANGUAGE:
                setLanguageRadioButton(preference);
                break;
            case AUTO:
                setAutoRadioButton();
                break;
            case CO2:
                setCO2Text();
                break;
            case LIGHT:
                setLightText();
                break;
            case AIR:
                setAirText();
                break;
            case SOIL:
                setSoilText();
                break;
        }
        return true;
    }

    /**
     * 设置选择语言的种类
     */
    private void setLanguageRadioButton(final Preference preference) {
        //获得单选按钮组
        mGroup = (RadioGroup) mLanguageETP.getDialog().findViewById(R.id.radioGroup1);
        mLanguageId = mLanguageETP.getSharedPreferences().getInt(LANGUAGEGROUP, 0);
        mGroup.check(mLanguageId);//单选按钮组默认选中id
        ((RadioButton) mGroup.getChildAt(0)).setText(R.string.chinese);
        ((RadioButton) mGroup.getChildAt(1)).setText(R.string.english);

        mGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio0) {
                    mLanguageId = R.id.radio0;
                } else if (checkedId == R.id.radio1) {
                    mLanguageId = R.id.radio1;
                }
            }
        });
    }

    /**
     * 设置控制状态的方式
     */
    private void setAutoRadioButton() {
        mGroup = (RadioGroup) mAutoETP.getDialog().findViewById(
                R.id.radioGroup1);
        mAutoId = mAutoETP.getSharedPreferences().getInt(AUTOGROUP, 0);
        mGroup.check(mAutoId);
        ((RadioButton) mGroup.getChildAt(0)).setText(R.string.manual);
        ((RadioButton) mGroup.getChildAt(1)).setText(R.string.auto);
        mGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio0) {
                    mAutoId = R.id.radio0;
                } else if (checkedId == R.id.radio1) {
                    mAutoId = R.id.radio1;
                }
            }
        });
    }

    /**
     * 显示CO2浓度的阀值
     *
     * //@param preference
     *            基础的自定义UI构造器
     */
    private void setCO2Text() {
        mCO2MinET = (EditText) mCO2ETP.getDialog().findViewById(
                R.id.major_min_value_edit_text);
        mCO2MaxET = (EditText) mCO2ETP.getDialog().findViewById(
                R.id.major_max_value_edit_text);

        mCO2MaxET.setText(mCO2ETP.getSharedPreferences().getInt(CO2_MAX, 0)
                + "");
        mCO2MinET.setText(mCO2ETP.getSharedPreferences().getInt(CO2_MIN, 0)
                + "");
    }

    /**
     * 显示光照强度的阀值
     *
     * //@param preference
     *            基础的自定义UI构造器
     */
    private void setLightText() {
        mLightMinET = (EditText) mLightETP.getDialog().findViewById(
                R.id.major_min_value_edit_text);
        mLightMaxET = (EditText) mLightETP.getDialog().findViewById(
                R.id.major_max_value_edit_text);

        mLightMaxET.setText(mLightETP.getSharedPreferences().getInt(LIGHT_MAX,
                0)
                + "");
        mLightMinET.setText(mLightETP.getSharedPreferences().getInt(LIGHT_MIN,
                0)
                + "");
    }

    /**
     * 显示空气温湿度的阀值
     *
     * //@param preference
     *            基础的自定义UI构造器
     */
    private void setAirText() {
        mAirTMinET = (EditText) mAirETP.getDialog().findViewById(
                R.id.major_min_value_edit_text);
        mAirTMaxET = (EditText) mAirETP.getDialog().findViewById(
                R.id.major_max_value_edit_text);
        mAirHMinET = (EditText) mAirETP.getDialog().findViewById(
                R.id.slave_min_value_edit_text);
        mAirHMaxET = (EditText) mAirETP.getDialog().findViewById(
                R.id.slave_max_value_edit_text);

        mAirTMaxET.setText(mAirETP.getSharedPreferences().getInt(AIR_T_MAX, 0)
                + "");
        mAirTMinET.setText(mAirETP.getSharedPreferences().getInt(AIR_T_MIN, 0)
                + "");
        mAirHMaxET.setText(mAirETP.getSharedPreferences().getInt(AIR_H_MAX, 0)
                + "");
        mAirHMinET.setText(mAirETP.getSharedPreferences().getInt(AIR_H_MIN, 0)
                + "");
    }

    /**
     * 显示土壤温湿度的阀值
     *
     * //@param preference
     *            基础的自定义UI构造器
     */
    private void setSoilText() {
        mSoilTMinET = (EditText) mSoilETP.getDialog().findViewById(
                R.id.major_min_value_edit_text);
        mSoilTMaxET = (EditText) mSoilETP.getDialog().findViewById(
                R.id.major_max_value_edit_text);
        mSoilHMinET = (EditText) mSoilETP.getDialog().findViewById(
                R.id.slave_min_value_edit_text);
        mSoilHMaxET = (EditText) mSoilETP.getDialog().findViewById(
                R.id.slave_max_value_edit_text);

        mSoilTMaxET.setText(mSoilETP.getSharedPreferences().getInt(SOIL_T_MAX,
                0)
                + "");
        mSoilTMinET.setText(mSoilETP.getSharedPreferences().getInt(SOIL_T_MIN,
                0)
                + "");
        mSoilHMaxET.setText(mSoilETP.getSharedPreferences().getInt(SOIL_H_MAX,
                0)
                + "");
        mSoilHMinET.setText(mSoilETP.getSharedPreferences().getInt(SOIL_H_MIN,
                0)
                + "");
    }
}
